home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Alignment restrictions...
- Date: Wed, 10 Jan 96 00:02:17 GMT
- Organization: none
- Message-ID: <821232137snz@genesis.demon.co.uk>
- References: <DKxHxG.EK1@ridgecrest.ca.us>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <DKxHxG.EK1@ridgecrest.ca.us>
- mcclung@owens.ridgecrest.ca.us "Scott McClung" writes:
-
- ...
-
- >I was porting some code out that had statements like:
- >
- >short value; /* 16 bit value */
- >char *ptr; /* 32 bit pointer, no alignment restrictions */
- >
- >value = *(short *)ptr;
- >
- >It worked on, say, Intel x86, or on values of ptr that happened to be
- >aligned (auto variables, in this case), but is not a general solution
- >on SPARC or other RISC architectures (MIPS and PA-RISC have similar
- >restrictions, if I recall.) The pointer in question happened to be
- >into an mmap()'ed image file, so the alignment is not guaranteed. Bus
- >errors.
- >
- >I replaced it with:
- >
- >value = *ptr << 8 | *(ptr + 1);
-
- What are the byte order conventions in the 'image file'? What you have here
- assumes big endian while the code at the top just assumes the byte order
- is the same as the target variable. In the latter case this problem is
- easily solved by:
-
- memcpy(&value, ptr, sizeof value);
-
- >Which works. I'd just like to find out how this is generally dealt
- >with in code... Actually, a magic compiler switch would be nice. :-)
- >(I'm working with gcc 2.7.2, BTW.) I'll probably replace the
- >statement above with some inline function that checks the alignment of
- >ptr, and acts appropriately. I guess I'm just looking for your
- >collective wisdom on this topic.
-
- I suspect that the tailored inline code that a good compiler can generate
- for memcpy, especially with a fixed, small size would be difficult to beat.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-